package com.example.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.AccountMapper;
import com.example.dao.OrderMapper;
import com.example.dto.StorageDTO;
import com.example.entity.Order;
import com.example.feign.StorageFeignClient;
import com.example.model.api.Result;
import com.example.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private StorageFeignClient storageFeignClient;



    @Override
    @GlobalTransactional
    public void purchase(String userId, String commodityCode, int orderCount, int money) {
        // 新增订单
        baseMapper.updateOrder(userId, commodityCode, orderCount, money);

        // 减库存
        StorageDTO storageDTO = new StorageDTO();
        storageDTO.setCommodityCode(commodityCode);
        storageDTO.setCount(orderCount);

        Result<String> stringResult = storageFeignClient.updateStorage(storageDTO);
        if (stringResult.getCode() != 200) {
            log.info(stringResult.getData());
        }
        // 故意引发异常用于测试
//            int a = 1 / 0;
//            System.out.println(a);

        // 减金额
        accountMapper.updateMoney(userId, money);
    }
}
